package com.xnyzc.lhy.task.mq;

import com.alibaba.fastjson.JSON;
import com.xnyzc.lhy.common.component.config.security.RocketConfig;
import com.xnyzc.lhy.common.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: bolt-servers
 * @description: MQ
 * @author: huxuekuo
 * @create: 2020-02-10 15:24
 **/
@Slf4j
@Component
public class MQProducer {

    /**
     * 生产者
     */
    @Autowired
    private DefaultMQProducer defaultMQProducer;

    @Autowired
    private RocketConfig rocketConfig;

    public void sendMsg(Object param, String tags, String topic) {
        sendMsg(param, tags, topic, 0);
    }

    /**
     * 向MQ中发送消息
     *
     * @param param
     * @param tags
     * @param topic
     * @param delayLevel delayLevel = 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     */
    public void sendMsg(Object param, String tags, String topic, int delayLevel) {
        log.info("进入发送消息方法(Start)");
        if (CheckUtil.strIsEmpty(topic)) {
            topic = rocketConfig.getTopic();
        }
        Message message = new Message(topic, tags, JSON.toJSONString(param).getBytes());
        if (delayLevel > 0) {
            message.setDelayTimeLevel(delayLevel);
        }
        try {
            SendResult send = defaultMQProducer.send(message);
            log.info("MQ发送消息 订单信息{},发送结果{}", JSON.toJSONString(param), send);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info("发送消息结束(End)");
    }
}
